/*
 * 页面主入口，负责模块拼装
 */
require( '$d/css/common.less' );
require( './style.less' );
define( [
  'require',
  'jquery',
  'header',
  'bigwe_utils',
  'message',
  'constants',
  'api',
  'ueditor',
  'styleFilter'
], function( require, $ ) {

  // 依赖注入
  var c = require( 'constants' );
  var bu = require( 'bigwe_utils' );
  var sf = require( 'styleFilter' );
  var udt = require( 'ueditor' );
  var BIGWE_API = require( 'api' );
  var ShowTitleMessage = require( 'message' );

  var filterSelector = '.js_material_container .js_mt_filter';

  // 初始化样式内容
  sf.init( {
    class: 'material_attention'
  }, {
    container: '.bwstyle_container .style_detail_container',
    scroll: '.bwstyle_container .style_detail_container',
    filter: filterSelector
  } );

  // 既存变量容错
  var md5 = bu.md5;
  var showTime = ShowTitleMessage.showTime;
  var tagsMaxCharLenth = c.tagsMaxCharLenth;
  var styleCol = $( '.edit_content .style_col' ),
    editorCol = $( '.edit_content .editor_col' ),
    previewCol = $( '.edit_content .preview_col' ),
    previewBody = $( '#art_preview_body' ),
    lumpArr = [ $( '.attention_guide', previewCol ), $( '.signature', previewCol ), $( '.readsource', previewCol ) ],
    thisApi = BIGWE_API.GZH_ART_STYLE,
    appid = bu.getUrlParam( 'appid' ),
    subData = {
      header: {},
      olink: {},
      qrcode: {}
    },
    currentTab = 'header',
    isContentChange = 0;

  if ( !appid ) {
    ShowTitleMessage.showWarning( '参数错误，请联系管理员', showTime );
    setTimeout( function() {
      window.location.href = '/my_account';
    }, 3e3 );
    return;
  }
  current_editor = udt.getEditor( 'styleEditor', {
    initialFrameHeight: 550,
    customtagHtml: '<div class="bodytips_outer"><span class="gray body-tips">在此输入内容</span></div>',
    editorStyle: '.view{height: 100%;} body.view{padding-right: 25px;position: absolute;top: 0}body.view::-webkit-scrollbar-track { background-color: #fff; opacity: 0; }body.view::-webkit-scrollbar { width: 8px; background-color: #ccc; }body.view::-webkit-scrollbar-thumb { background: #ccc; border-radius: 6px; }',
    toolbars: [
      [ "undo", "redo", "|", /*"paragraph", "|",*/ "fontfamily",
        "fontsize", 'blockquote', "horizontal", "|", "removeformat", 'formatmatch', "autotypeset",
        'background', 'linebreak', "|", 'spechars',
        'subscript', 'superscript', "bold",
        "italic", "underline", 'strikethrough', "forecolor", "shadowcolor", "backcolor", "|",
        "indent", "justifyleft", "justifycenter", "justifyright", 'justifyjustify',
        "rowspacingtop", 'rowspacingbottom', "lineheight", "|", 'insertorderedlist',
        'insertunorderedlist', 'emotion', 'searchreplace', 'link', 'simpleupload', 'insertimage', 'message', 'imgstyle'
      ]
    ],
    autoHeightEnabled: false
  } );

  window.onbeforeunload = function( event ) {
    if ( isContentChange ) {
      return '即将离开页面，请确认您编辑的内容已经保存';
    }
  }
  var thisUtils = {
    artPreviewBody: function() {
      var content = subData[ currentTab ].content = this.getContent();
      $( this.body ).mediaSrcAttr();
      $( '[secttion-selector="' + currentTab + '"]', previewBody )
        .html( $( content ).mediaSrcAttr() )
        .find( 'img[data-ratio]' )
        .css( {
          'height': 'auto'
        } );
    },
    dataFullToPage: function( data ) {
      if ( data ) {
        subData = data;
        current_editor.setContent( subData[ currentTab ].content || '' );
        for ( var key in subData ) {
          var contentObj = subData[ key ];
          $( '[secttion-selector="' + key + '"]', previewBody ).html( contentObj.content || '' );
        }
        previewBody.mediaFormat().mediaSrcAttr();
      }
    },
    autoSave: {
      intervalID: '',
      storageKey: md5( 'bigweArtStyle' + $( '#frm_header #user-id-bg' ).val() + appid ),
      start: function() {
        var _this = this;
        if ( !this.intervalID ) {
          $( '.autosave .autosave-text', editorCol ).fadeIn();
          this.intervalID = setInterval( function() {
            window.localStorage.setItem( _this.storageKey, JSON.stringify( subData ) );
          }, 1e3 );
          return !0;
        }

        return 0;
      },
      clear: function() {
        if ( this.intervalID ) {
          clearInterval( this.intervalID );
          delete this.intervalID;
        }
        window.localStorage.removeItem( this.storageKey );
      },
      fullDataToPage: function() {
        thisUtils.dataFullToPage( this._getLocalStorage() );
      },
      _getLocalStorage: function() {
        var thisStorage = window.localStorage.getItem( this.storageKey );
        if ( thisStorage ) {
          return $.parseJSON( thisStorage );
        }
        return undefined;
      },
      showDraftLink: function() {
        if ( this._getLocalStorage() ) {
          $( '.autosave .draft-text', editorCol ).fadeIn( 500 );
        }
      }
    }
  }

  ;
  ( function( self, ed ) {
    //  样式列
    self.on( 'click', '.mystyle_nav li', function() {
      $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
    } ).on( 'click', filterSelector, function() {
      currentTab = $( this ).attr( 'trigger-target' );
      editorCol.find( '.edit_style_type .type_item[data-section="' + currentTab + '"]' ).addClass( 'selected' ).siblings().removeClass( 'selected' );
      ed.setContent( subData[ currentTab ].content || '' );
    } );

    $( '.style_columns', self ).bwColumns( [ /*'我的样式', */ '素材样式' ], function( index ) {
      var animateTarget = $( '.style_type_container', self );
      if ( animateTarget.hasClass( 'active' ) ) {
        animateTarget.removeClass( 'active' );
      } else {
        animateTarget.addClass( 'active' );
      }
    } );

  }( styleCol, current_editor ) );

  ;
  ( function( self, ed ) {

    self.on( 'click', '.edit_style_type .type_item', function() {

      $( '[trigger-target="' + $( this ).data( 'section' ) + '"]' ).trigger( 'click' );

    } ).on( 'click', '.style_bar_control', function() {
      if ( self.hasClass( 'active' ) ) {
        self.removeClass( 'active' );
        $( this ).removeClass( 'active' );
      } else {
        self.addClass( 'active' );
        $( this ).addClass( 'active' );
      }
    } ).on( 'click', '.autosave .draft-text', function() {
      thisUtils.autoSave.fullDataToPage();
    } );

    ed.addListener( 'blur', function() {
      thisUtils.artPreviewBody.call( this );
    } );

    ed.addListener( 'contentChange', function() {
      thisUtils.artPreviewBody.call( this );
      if ( this.isFirstChange ) {
        thisUtils.autoSave.start();
        isContentChange = !0;
      }
      this.isFirstChange = !0;
    } );

  }( editorCol, current_editor ) );

  ;
  ( function( self, ec ) {

    self.on( 'click', '[secttion-selector]', function() {
      $( '.edit_style_type [data-section="' + $( this ).attr( 'secttion-selector' ) + '"]', ec ).trigger( 'click' );
    } );

    $( '.art_date', self ).text( new Date().format( 'yyyy-MM-dd' ) );

    $( '.modal_section', self ).tooltip( {
      'container': 'body'
    } );
  }( previewCol, editorCol ) );

  // other
  ;
  ( function( ed ) {
    var editorDtd = $.Deferred();

    function editorReady( dtd ) {

      ed.ready( function() {
        thisUtils.autoSave.showDraftLink();

        // 该异步对象完成
        dtd.resolve();
      } );
      // 承诺的，外部无法改变其状态
      return dtd.promise();
    }

    $.when( $.ajax( thisApi.GET_DEFAULT + '?appid=' + appid ), editorReady( editorDtd ) ).then( function( data ) {
      var resp = data[ 0 ] ? $.parseJSON( data[ 0 ] ) : '';
      if ( !resp.ret ) {
        thisUtils.dataFullToPage( resp.data );
      } else {
        ShowTitleMessage.showWarning( resp.msg || '发生错误', showTime );
      }
    } );


    $( '.fixed_btn_group' ).on( 'click', '.save_style', function() {
      var _this = $( this );
      _this.prop( 'disabled', 'disabled' );
      ShowTitleMessage.show( '正在保存' );
      $.ajax( {
        url: thisApi.SAVE_DEFAULT,
        type: 'post',
        data: {
          appid: appid,
          data: JSON.stringify( subData )
        },
        success: function( data ) {
          if ( !data.ret ) {
            ShowTitleMessage.show( '保存成功！', showTime );
            isContentChange = 0;
            thisUtils.autoSave.clear();
          }
        },
        complete: function() {
          _this.removeAttr( 'disabled' );
        }
      } );
    } );
  }( window.current_editor ) );

} );
